//
//  PPXCActionManager.m
//  XPPXcodePlugin
//
//  Created by yoyokko on 10-8-15.
//  Copyright 2010 yoyokko@gmail.com. All rights reserved.
//

#import "PPXCActionManager.h"
#import "XPPXcodePlugin.h"
#import "GTMObjC2Runtime.h"
#import "XCActionManager.h"
#import "PBXExtendedMenuItem.h"
#import "PBXExtendedMenu.h"

@implementation PPXCActionManager

// Register our class to perform the swizzle once the plugin has finished
// loading.
+ (void)load {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[XPPXcodePlugin registerSwizzleClass:self];
	[pool release];
}

- (id)init {
	if ((self = [super init])) {
		swizzleMethods([self class], [XCActionManager class], @selector(xpp_menuNeedsUpdate:), @selector(menuNeedsUpdate:));
		swizzleMethods([self class], [XCActionManager class], @selector(xpp_validateMenuItem:), @selector(validateMenuItem:));
		swizzleMethods([self class], [XCActionManager class], @selector(xpp_selectionAtLevel:), @selector(selectionAtLevel:));
		swizzleMethods([self class], [XCActionManager class], @selector(xpp_contextMenuForType:), @selector(contextMenuForType:));
	}
	return self;
}

- (void) xpp_menuNeedsUpdate:(NSMenu *) fp8
{
	PBXExtendedMenuItem *menuItem = (PBXExtendedMenuItem *)[fp8 itemAtIndex:2];
	if ([[menuItem title] isEqualToString:@"Auto Accessorizer"]) {
		//menuItem.target = [[XCActionManager defaultActionManager] selectionAtLevel:@"XCActiveSelectionLevel"];
		if (![self validateMenuItem:menuItem])
		{
			[fp8 removeItemAtIndex:2];
		}
	}
	[self xpp_menuNeedsUpdate:fp8];
}

- (BOOL) xpp_validateMenuItem:(id)fp8
{
	if ([[fp8 title] isEqualToString:@"Auto Accessorizer"]) {
		if ([[[XCActionManager defaultActionManager] selectionAtLevel:@"XCActiveSelectionLevel"] xpp_validateMenuItem_autoAccessorizer:fp8] != 1)
			return NO;
		return YES;
	}
	BOOL ret = [self xpp_validateMenuItem:fp8];
	return  ret;
}

- (PBXExtendedMenu *) xpp_contextMenuForType:(int) type
{
	PBXExtendedMenu *menu = [self xpp_contextMenuForType:type];
	if (type == 0 && ![menu itemWithTag:100]) 
	{
		PBXExtendedMenuItem *menuItem = [[PBXExtendedMenuItem alloc] initWithTitle:@"Auto Accessorizer"
																			action:@selector(autoAccessorizer:)
																	 keyEquivalent:@"BA"];
		menuItem.tag = 100;
		[menuItem setEnabled:YES];
		[menu insertItem:menuItem atIndex:2];
		[menuItem release];
	}
	return menu;
}


- (id) xpp_selectionAtLevel:(id)arg1
{
	id sel = [self xpp_selectionAtLevel:arg1];
	return sel;
}

@end
